﻿using System;
using System.Web.Mvc;
using System.Web.Security;
using QLDV.Infrastructure;
using QLDV.Models;
using QLDV.ViewModels;

namespace QLDV.Controllers
{
    public class AccountController : BaseController
    {
        public ActionResult LogOn()
        {
            if (Request.IsAuthenticated)
                return RedirectToAction("Index", "Home");
            var model = new LogOnModel
            {
                ReturnUrl = Request.QueryString["ReturnUrl"]
            };
            return View(model);
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model)
        {
            if (!ModelState.IsValid)
                return View(model);

            var user = Repository.ValidateUser(model.LoginName, model.Password);
            if (user != null)
            {
                return StoreAuthCookieAndRedirect(user.TenDangNhap, model.ReturnUrl, model.RememberMe, user.LOAITAIKHOAN1.Id_LoaiTK);
            }
            ModelState.AddModelError(string.Empty, "Invalid Tên đăng nhập and/or password");
            return View("LogOn");
        }

        private ActionResult StoreAuthCookieAndRedirect(string userID, string returnUrl, bool remember, int id_loaitk)
        {
            FormsAuthentication.SetAuthCookie(userID, remember);
            if(string.IsNullOrEmpty(returnUrl))
            {
                if(id_loaitk == 1)
                    return RedirectToAction("Index", "DoanVien");
                return RedirectToAction("Index", "Home");
            }
            return Redirect(returnUrl.UrlDecode());
        }

        [HttpGet]
        public ActionResult LogOff(string returnUrl)
        {
            FormsAuthentication.SignOut();
            returnUrl = string.IsNullOrEmpty(returnUrl) ? "/" : returnUrl;
            return Redirect(returnUrl.UrlDecode());
        }

    }
}
